﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nebular.ExpenseManagement.Infrastructure;

namespace Nebular.ExpenseManagement.Model
{
    [Serializable]
    public class User : Principal, IUser
    {
        readonly string _email;
        readonly IPrincipal _approveBy;
        readonly IEnumerable<ICreditCard> _creditCards;
        readonly IEnumerable<ITransaction> _transactionsToApprove;
        readonly IEnumerable<ITransaction> _transactionsToProcess;

        internal User(Guid id, string name, string email, IPrincipal approveBy,
            IEnumerable<ICreditCard> creditCards,
            IEnumerable<ITransaction> transactionsToApprove,
            IEnumerable<ITransaction> transactionsToProcess)
            : base(id, name)
        {
            _email = email;
            _approveBy = approveBy;
            _creditCards = creditCards;
            _transactionsToApprove = transactionsToApprove;
            _transactionsToProcess = transactionsToProcess;
        }

        

        internal User(xpPrincipal user) 
            : this(
            user.Id, 
            user.Name, 
            "",//user.aspnet_Membership.Email, // HACK
            Principal.FromExpPrincipal(user.ApproveBy),            
            CreditCard.Convert(user.Creditcards),
            new ITransaction[] {},
            new ITransaction[] {})
        {
            if (user.PrincipalType != "u")
                throw new ArgumentException("Principal must be of user type");
        }
        
        #region IUser Members

        public string Email
        {
            get { return _email; }
        }

        public IPrincipal ApproveBy
        {
            get { return _approveBy; }
        }

        public IEnumerable<ICreditCard> CreditCards
        {
            get { return _creditCards; }
        }

        public IUser CreateCreditCard(string newCreditCard)
        {
            throw new NotImplementedException();
        }

        public IProcessedTransaction Approve(ITransaction transaction)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<ITransaction> TransactionsToApprove
        {
            get
            {
                return _transactionsToApprove;
            }
        }

        public IEnumerable<ITransaction> TransactionsToProcess
        {
            get {
                return _transactionsToProcess;
            }
        }

        #endregion

        internal static IEnumerable<IUser> Convert(IEnumerable<xpPrincipal> users)
        {
            foreach (var user in users)
                yield return new User(user);
        }
    }
}
